<template>
  <div class="news-edit page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <router-link to="/news">
            <span class="text">新闻管理</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">{{ isEdit ? '编辑新闻' : '添加新闻' }}</span>
        </div>
      </div>
      <h1 class="page-title">{{ isEdit ? '编辑新闻' : '添加新闻' }}</h1>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <form class="v-form" @submit.prevent="submitForm">
        <!-- 基本信息卡片 -->
        <div class="v-card">
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
          <div class="card-body">
            <div class="form-grid">
              <!-- 标题 -->
              <div class="form-group">
                <label class="form-label">标题</label>
                <input
                  v-model="formData.title"
                  type="text"
                  class="form-input"
                  placeholder="请输入新闻标题"
                  required
                />
              </div>

              <!-- 作者 -->
              <div class="form-group">
                <label class="form-label">作者</label>
                <input
                  v-model="formData.author"
                  type="text"
                  class="form-input"
                  placeholder="请输入作者"
                />
              </div>

              <!-- 发布日期 -->
              <div class="form-group">
                <label class="form-label">发布日期</label>
                <input
                  v-model="formData.publish_date"
                  type="date"
                  class="form-input"
                  placeholder="请选择发布日期"
                />
              </div>

              <!-- 排序 -->
              <div class="form-group">
                <label class="form-label">排序</label>
                <input
                  v-model="formData.sort_order"
                  type="number"
                  class="form-input"
                  placeholder="请输入排序值"
                  min="0"
                />
              </div>

              <!-- 全局置顶 -->
              <div class="form-group">
                <label class="form-label">全局置顶</label>
                <div class="toggle-wrapper">
                  <div class="checkbox-wrapper-34">
                    <input
                      class="tgl tgl-ios"
                      id="is-top-toggle"
                      type="checkbox"
                      v-model="formData.is_top"
                      true-value="1"
                      false-value="0"
                    />
                    <label class="tgl-btn" for="is-top-toggle"></label>
                  </div>
                </div>
              </div>

              <!-- 首页显示 -->
              <div class="form-group">
                <label class="form-label">首页显示</label>
                <div class="toggle-wrapper">
                  <div class="checkbox-wrapper-34">
                    <input
                      class="tgl tgl-ios"
                      id="is-home-toggle"
                      type="checkbox"
                      v-model="formData.is_home"
                      true-value="1"
                      false-value="0"
                    />
                    <label class="tgl-btn" for="is-home-toggle"></label>
                  </div>
                </div>
              </div>

              <!-- 新闻页置顶 -->
              <div class="form-group">
                <label class="form-label">新闻页置顶</label>
                <div class="toggle-wrapper">
                  <div class="checkbox-wrapper-34">
                    <input
                      class="tgl tgl-ios"
                      id="is-news-top-toggle"
                      type="checkbox"
                      v-model="formData.is_news_top"
                      true-value="1"
                      false-value="0"
                    />
                    <label class="tgl-btn" for="is-news-top-toggle"></label>
                  </div>
                </div>
              </div>

              <!-- 封面图片 -->
              <div class="form-group full-width">
                <label class="form-label">封面图片</label>
                <ImgUploader
                  v-model="formData.cover_image"
                  :max-size="5"
                  accept="image/*"
                />
                <div class="form-hint">建议尺寸：800x450，大小不超过5MB</div>
              </div>

              <!-- 简要内容 -->
              <div class="form-group full-width">
                <label class="form-label">简要内容</label>
                <textarea
                  v-model="formData.brief"
                  class="form-textarea"
                  placeholder="请输入新闻简要内容（如不填写，将自动从内容中截取40个中文字符）"
                  rows="4"
                ></textarea>
                <div class="form-hint">简要内容将显示在新闻列表页，最多200个字符</div>
              </div>

              <!-- 新闻内容 -->
              <div class="form-group full-width">
                <label class="form-label">新闻内容</label>
                <div id="editor-container" style="height: 400px;"></div>
              </div>

              <!-- 创建时间 -->
              <div class="form-group" v-if="isEdit">
                <label class="form-label">创建时间</label>
                <input
                  type="text"
                  class="form-input"
                  :value="formatTimestamp(formData.created_at)"
                  disabled
                />
              </div>

              <!-- 更新时间 -->
              <div class="form-group" v-if="isEdit">
                <label class="form-label">更新时间</label>
                <input
                  type="text"
                  class="form-input"
                  :value="formatTimestamp(formData.updated_at)"
                  disabled
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <button type="submit" class="v-button primary">提交保存</button>
          <button type="button" class="v-button" @click="goBack">返回</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { get, post, upload } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vToast } from "@/plugins/vToast";
import ImgUploader from "@/components/ImageUploader.vue";
import E from "wangeditor";

const route = useRoute();
const router = useRouter();

// 富文本编辑器实例
const editor = ref(null);

const isEdit = computed(() => route.name === 'NewsEdit');

// 表单数据
const formData = ref({
  id: null,
  title: "",
  brief: "",
  content: "",
  cover_image: "",
  author: "",
  publish_date: "",
  sort_order: "0",
  is_top: "0",
  is_home: "0",
  is_news_top: "0",
  created_at: null,
  updated_at: null,
});

// 初始化富文本编辑器
const initEditor = () => {
  nextTick(() => {
    if (editor.value) {
      editor.value.destroy();
    }

    const editorInstance = new E("#editor-container");
    editorInstance.config.zIndex = 100;
    editorInstance.config.uploadImgShowBase64 = true;

    // 自定义图片上传
    editorInstance.config.customUploadImg = function (resultFiles, insertImgFn) {
      const formData = new FormData();
      formData.append("file", resultFiles[0]);

      upload("/upload/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then((res) => {
          if (res.code === 200) {
            insertImgFn(res.data.url);
          } else {
            throw new Error(res.msg || "上传失败");
          }
        })
        .catch((error) => {
          console.error("上传失败", error);
          vToast.error("图片上传失败: " + (error.message || "未知错误"));
        });
    };

    editorInstance.config.onchange = (html) => {
      formData.value.content = html;
    };

    editorInstance.create();
    editorInstance.txt.html(formData.value.content || "");
    editor.value = editorInstance;
  });
};

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 获取新闻详情
const fetchNewsDetail = async (id) => {
  try {
    const res = await get("/news/detail", { id });
    if (res.code === 200 && res.data) {
      formData.value = {
        id: res.data.id,
        title: res.data.title || "",
        brief: res.data.brief || "",
        content: res.data.content || "",
        cover_image: res.data.cover_image || "",
        author: res.data.author || "",
        publish_date: res.data.publish_date || "",
        sort_order: res.data.sort_order || "0",
        is_top: res.data.is_top || "0",
        is_home: res.data.is_home || "0",
        is_news_top: res.data.is_news_top || "0",
        created_at: res.data.created_at,
        updated_at: res.data.updated_at,
      };
      
      // 初始化编辑器并设置内容
      initEditor();
    } else {
      vToast.error(res.msg || "获取新闻详情失败");
    }
  } catch (error) {
    vToast.error("获取新闻详情失败");
    console.error(error);
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证逻辑
    if (!formData.value.title) {
      vToast.warning("请输入新闻标题");
      return;
    }
    
    if (!formData.value.content) {
      vToast.warning("请输入新闻内容");
      return;
    }

    // 准备提交数据
    const data = { ...formData.value };
    
    // 如果是新增模式，移除ID
    if (!isEdit.value) {
      delete data.id;
      delete data.created_at;
      delete data.updated_at;
    }

    const api = isEdit.value ? "/news/update" : "/news/add";
    const res = await post(api, data);

    if (res.code === 200) {
      vToast.success(isEdit.value ? "新闻更新成功" : "新闻添加成功");
      router.push("/news");
    } else {
      vToast.error(res.msg || "操作失败");
    }
  } catch (error) {
    vToast.error("提交失败");
    console.error(error);
  }
};

// 返回
const goBack = () => {
  router.push("/news");
};

// 初始化
onMounted(() => {
  initEditor();
  
  if (isEdit.value && route.params.id) {
    fetchNewsDetail(route.params.id);
  } else {
    // 设置默认值
    formData.value.sort_order = "0";
    formData.value.is_top = "0";
    formData.value.is_home = "0";
    formData.value.is_news_top = "0";
    // 设置默认日期为今天
    const today = new Date();
    formData.value.publish_date = today.toISOString().split('T')[0];
  }
});

// 销毁编辑器实例
onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
    editor.value = null;
  }
});
</script>

<style scoped lang="less">
.news-edit {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .form-container {
    width: 100%;
    padding: 20px;
  }

  .v-card {
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    
    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #eee;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .card-body {
      padding: 20px;
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    
    .form-group {
      margin-bottom: 15px;
      
      &.full-width {
        grid-column: 1 / -1;
      }
      
      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .form-input {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
        
        &:disabled {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }

      .form-textarea {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        min-height: 100px;
        resize: vertical;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
      }
      
      .form-hint {
        margin-top: 8px;
        font-size: 12px;
        color: #999;
      }
      
      .toggle-wrapper {
        display: flex;
        align-items: center;
        height: 40px;
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
    
    .v-button {
      min-width: 120px;
      height: 40px;
      padding: 0 20px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      
      &.primary {
        background-color: var(--v-theme);
        color: white;
        border: none;
        
        &:hover {
          background-color: var(--v-sidebar-background);
        }
      }
      
      &:not(.primary) {
        background-color: #fff;
        border: 1px solid #ddd;
        color: #333;
        
        &:hover {
          border-color: var(--v-theme);
          color: var(--v-theme);
        }
      }
    }
  }
}

/* 开关样式 */
.checkbox-wrapper-34 {
  --blue: var(--v-theme);
  --g08: #E1E5EB;
  --g04: #848ea1;
}

.checkbox-wrapper-34 .tgl {
  display: none;
}
.checkbox-wrapper-34 .tgl,
.checkbox-wrapper-34 .tgl:after,
.checkbox-wrapper-34 .tgl:before,
.checkbox-wrapper-34 .tgl *,
.checkbox-wrapper-34 .tgl *:after,
.checkbox-wrapper-34 .tgl *:before,
.checkbox-wrapper-34 .tgl + .tgl-btn {
  box-sizing: border-box;
}
.checkbox-wrapper-34 .tgl::selection,
.checkbox-wrapper-34 .tgl:after::selection,
.checkbox-wrapper-34 .tgl:before::selection,
.checkbox-wrapper-34 .tgl *::selection,
.checkbox-wrapper-34 .tgl *:after::selection,
.checkbox-wrapper-34 .tgl *:before::selection,
.checkbox-wrapper-34 .tgl + .tgl-btn::selection {
  background: none;
}
.checkbox-wrapper-34 .tgl + .tgl-btn {
  outline: 0;
  display: block;
  width: 57px;
  height: 27px;
  position: relative;
  cursor: pointer;
  user-select: none;
  font-size: 12px;
  font-weight: 400;
  color: #fff;
}
.checkbox-wrapper-34 .tgl + .tgl-btn:after,
.checkbox-wrapper-34 .tgl + .tgl-btn:before {
  position: relative;
  display: block;
  content: "";
  width: 44%;
  height: 100%;
}
.checkbox-wrapper-34 .tgl + .tgl-btn:after {
  left: 0;
}
.checkbox-wrapper-34 .tgl + .tgl-btn:before {
  display: inline;
    position: absolute;
    top: 6px;
}
.checkbox-wrapper-34 .tgl:checked + .tgl-btn:after {
  left: 56.5%;
}

.checkbox-wrapper-34 .tgl-ios + .tgl-btn {
  background: var(--g08);
  border-radius: 20rem;
  padding: 2px;
  transition: all 0.4s ease;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
}
.checkbox-wrapper-34 .tgl-ios + .tgl-btn:after {
  border-radius: 2em;
  background: #fff;
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
}
.checkbox-wrapper-34 .tgl-ios + .tgl-btn:before {
  content: "否";
  left: 32px;
  color: var(--g04);
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.checkbox-wrapper-34 .tgl-ios + .tgl-btn:active {
  box-shadow: inset 0 0 0 30px rgba(0, 0, 0, 0.1);
}
.checkbox-wrapper-34 .tgl-ios + .tgl-btn:active:after {
  padding-right: 0.4em;
}
.checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn {
  background: var(--blue);
}
.checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn:active {
  box-shadow: inset 0 0 0 30px rgba(0, 0, 0, 0.1);
}
.checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn:active:after {
  margin-left: -0.4em;
}
.checkbox-wrapper-34 .tgl-ios:checked + .tgl-btn:before {
  content: "是";
  left: 11px;
  color: #fff;
}
</style>